from bs4 import BeautifulSoup
from urllib.parse import quote


def get_work_info(res_text: str, page_url: str) -> dict:
    result_dict = {}

    soup = BeautifulSoup(res_text, 'lxml')
    # 作品id
    result_dict['illust_id'] = page_url.split('/illust/')[1]

    s_illust = '.illust-pages > li > a > img'
    # 作品内所有图片的源地址列表
    result_dict['illust_url_list'] = \
        [str(element['src']).split('?')[0].replace('/regular/', '/original/').replace('_master1200.jpg', '.png')
         for element in soup.select(s_illust)]

    s_title = '.illust-rang h2'
    # 作品名，使用了url编码
    result_dict['illust_title'] = quote(str(soup.select_one(s_title).text))

    s_tag = '.tags li > a'
    # tag列表，使用了url编码
    result_dict['illust_tag_list'] = [quote(str(element.text)) for element in soup.select(s_tag)]

    s_cnt_elements = '.count-content > li dd'
    # 点赞数
    result_dict['illust_like_cnt'] = str(soup.select(s_cnt_elements)[0].text).replace(',', '').strip()
    # 收藏数
    result_dict['illust_collect_cnt'] = str(soup.select(s_cnt_elements)[1].text).replace(',', '').strip()

    s_upload_date = '.upload-date'
    # 上传日期，上传时间
    result_dict['illust_upload_date'], result_dict['illust_upload_time'] = str(
        soup.select_one(s_upload_date).text).strip().split(' ', 1)

    s_author_url = '.user-box > a'
    # 作者主页链接，如’/user/27517‘
    result_dict['author_url'] = soup.select_one(s_author_url)['href']

    s_author_name = '.user-box .ellipsis > a'
    # 作者名，使用了url编码
    result_dict['author_name'] = quote(str(soup.select_one(s_author_name).text))

    s_author_id = '.illust-desc.ellipsis'
    # 作者id
    result_dict['author_id'] = str(soup.select_one(s_author_id).text).split(':')[1]

    return result_dict


def get_page_max_num(res_text: str) -> int:
    soup = BeautifulSoup(res_text, 'lxml')

    s_max_page = '.el-pager > .number'
    return int(soup.select(s_max_page)[-1].text)


def get_url_list(res_text: str, s_url: str) -> list[str]:
    soup = BeautifulSoup(res_text, 'lxml')

    return [element['href'] for element in soup.select(s_url)]
